package com.njrsrc.android.app;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;

import com.njrsrc.R;
import com.njrsrc.common.exception.ContextCrashHandler;
import com.njrsrc.common.utils.ActivityStack;

/**
 * 
 * @author Oliverzhu 2013/4/14
 */
public class BaseActivity extends Activity {
	protected Context context;

	protected Handler mProgressDialogHandler = new MainThreadHandler(Looper.getMainLooper());

	/** 消息标志 */
	/** 打开loading框 */
	public static final int SHOWPROGRESSDIALOG = 1;

	/** 关闭loading框 */
	public static final int CLOSEPROGRESSDIALOG = 2;

	private ProgressDialog mProgressDialog;

	/** 执行一些非UI线程 */
	protected static ExecutorService exec;
	
	protected DisplayMetrics dm;
	
	protected static SharedPreferences preferences;
	
	private static final String SPF_NAME = "njrsrc";

	/**
	 * 主线程Handler对象
	 * 
	 * @author Oliverzhu
	 * 
	 */
	class MainThreadHandler extends Handler {
		public MainThreadHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SHOWPROGRESSDIALOG:
				showProgressDialog();
				break;
			case CLOSEPROGRESSDIALOG:
				dismissProgressDialog();
				break;
			}
			super.handleMessage(msg);
		}
	}

	public Handler getmProgressDialogHandler() {
		return mProgressDialogHandler;
	}

	protected String getLoadingString() {
		return getString(R.string.loading);
	}

	private ProgressDialog showProgressDialog() {
		if (mProgressDialog == null) {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setIcon(R.drawable.m_prompt);
			dialog.setMessage(getLoadingString());
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			mProgressDialog = dialog;
		}

		if (!mProgressDialog.isShowing()) {
			mProgressDialog.show();
		}
		return mProgressDialog;
	}

	private void dismissProgressDialog() {
		try {
			if (mProgressDialog != null && mProgressDialog.isShowing()) {
				mProgressDialog.dismiss();
			}
		} catch (IllegalArgumentException e) {
			// We don't mind. android cleared it for us.
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActivityStack.put(this);
		context = this;
		
		dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);// 获取分辨率
		
		preferences = getSharedPreferences(SPF_NAME, MODE_PRIVATE);

		exec = Executors.newCachedThreadPool();

		// 注册异常处理机
		Thread.setDefaultUncaughtExceptionHandler(new ContextCrashHandler(this));
	}
	
    protected void onDestroy() {
		super.onDestroy();

		ActivityStack.getStack().remove(this);
	}
}